// pages/goods_detail/goods_detail.js
import { request } from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 储存商品数据
    goods_detail: {},
    isCollect: false
  },
  // 全局商品数据
  goods_info: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    // 获取页面栈
    let pages = getCurrentPages()
    // 索引最大的就是当前页面
    let currentPages = pages[pages.length - 1]
    const { goods_id } = currentPages.options
    this.getGoodsDetail(goods_id)
  },
  // 发送请求商品数据
  async getGoodsDetail(goods_id) {
    const res = await request({ url: '/goods/detail', data: { goods_id } })
    this.goods_info = res
    // 获取缓存中收藏的商品数组
    let collect = wx.getStorageSync("collect") || []
    // 判断当前商品是否被收藏
    let isCollect = collect.some(v => v.goods_id === this.goods_info.goods_id)
    this.setData({
      goods_detail: {
        goods_name: res.goods_name,
        goods_price: res.goods_price,
        goods_introduce: res.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: res.pics
      },
      isCollect
    })
  },
  handlePreviewImage(e) {
    const current = e.currentTarget.dataset.url
    const urls = this.goods_info.pics.map(v => v.pics_mid)
    wx.previewImage({
      current,
      urls
    });
  },
  // 添加商品
  addGood() {
    // 读取本地数据
    let cart = wx.getStorageSync('cart') || []
    // 
    let index = cart.findIndex(v => v.goods_id === this.goods_info.goods_id)
    if (index === -1) {
      this.goods_info.num = 1
      this.goods_info.checked = true
      cart.push(this.goods_info)
    } else {
      cart[index].num++
    }
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      mask: true
    })
  },
  // 点击收藏商品
  handleCollect() {
    let isCollect = false
    let collect = wx.getStorageSync("collect") || []
    let index = collect.findIndex(v => v.goods_id === this.goods_info.goods_id)
    if (index !== -1) {
      collect.splice(index, 1)
      isCollect = false
      wx.showToast({
        title: '取消成功！',
        icon: 'success',
        mask: true
      })
    } else {
      collect.push(this.goods_info)
      isCollect = true
      wx.showToast({
        title: '收藏成功！',
        icon: 'success',
        mask: true
      })
    }
    wx.setStorageSync("collect", collect)
    this.setData({
      isCollect
    })
  }
})